﻿using UnityEngine;

[RequireComponent(typeof(UIGrid))]
public class ItemCenterGrid : MonoBehaviour 
{
    public float m_Strength = 8;
    private UIScrollView mScroll;
    private UIPanel mPanel;
    private UIGrid mGrid;

    private float minPos;
    private float maxPos;
    private int sceneCount;

    private void Awake()
    {
        mScroll = GetComponentInParent<UIScrollView>();
        mPanel = mScroll.GetComponent<UIPanel>();
        mGrid = GetComponent<UIGrid>();
        
        float num; int maxPer = mGrid.maxPerLine;
        if (maxPer <= 0) { maxPer = 1; }

        if (mScroll.canMoveHorizontally)
        {
            minPos = mPanel.clipOffset.x;
            num = mPanel.width / mGrid.cellWidth;
        }
        else
        {
            minPos = mPanel.clipOffset.y;
            num = mPanel.height / mGrid.cellHeight;
        }
        sceneCount = Mathf.FloorToInt(num) * maxPer;
        if (transform.childCount > 0) { InitData(); }
    }

    /// <summary>
    /// 列表变化时刷新位置和滑动属性
    /// </summary>
    public void InitData()
    {
        int dataCount = transform.childCount - 1;
        mGrid.Reposition(); mScroll.ResetPosition();
        bool Drag = sceneCount <= transform.childCount;
        Utility.SetBehaviour<UIDragScrollView>(transform, Drag);
        
        if (mScroll.canMoveHorizontally)
        {
            maxPos = dataCount * mGrid.cellWidth - minPos;
        }
        else
        {
            maxPos = dataCount * mGrid.cellHeight + minPos;
        }
    }
    
    /// <summary>
    /// 列表位置居中排序
    /// </summary>
    /// <param name="target"></param>
    public void CenterOn(Transform target)
    {
        Transform panelTrans = mPanel.transform;
        Vector3[] corners = mPanel.worldCorners;
        Vector3 panelCenter = (corners[2] + corners[0]) * 0.5f;
        Vector3 cp = panelTrans.InverseTransformPoint(target.position);
        Vector3 cc = panelTrans.InverseTransformPoint(panelCenter);

        Vector3 localOffset = cp - cc;
        localOffset.z = 0f;
        if (!mScroll.canMoveHorizontally)
            localOffset.x = 0f;
        if (!mScroll.canMoveVertically)
            localOffset.y = 0f;

        Vector3 offset = panelTrans.localPosition;
        Vector4 co = mPanel.clipOffset;
        co.x += localOffset.x;
        co.y += localOffset.y;

        if (mScroll.canMoveHorizontally)
        {
            co.x = Mathf.Min(co.x, +maxPos);
            co.x = Mathf.Max(co.x, minPos);
            offset.x = -co.x;
        }
        else
        {
            co.y = Mathf.Min(co.y, minPos);
            co.y = Mathf.Max(co.y, -maxPos);
            offset.y = -co.y;
        }
        SpringPanel.Begin(mPanel.gameObject, offset, m_Strength);
    }
}